package cn.hg.solon.youcan.framework.directive.system;

import static cn.hg.solon.youcan.system.entity.table.SysDictTableDef.SYS_DICT;

import java.util.List;
import java.util.function.Supplier;

import org.apache.ibatis.solon.annotation.Db;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.mybatisflex.core.query.QueryOrderBy;
import com.mybatisflex.core.query.QueryWrapper;

import cn.hg.solon.youcan.common.constant.CacheConstants;
import cn.hg.solon.youcan.common.enums.BeanStatus;
import cn.hg.solon.youcan.framework.cache.YoucanCacheService;
import cn.hg.solon.youcan.framework.directive.BaseDirective;
import cn.hg.solon.youcan.system.entity.SysDict;
import cn.hg.solon.youcan.system.mapper.SysDictMapper;

/**
 * @author 胡高
 */
@Component("view:" + DictTypeDirective.DIRECTIVE_NAME)
public class DictTypeDirective extends BaseDirective {

    public static final String DIRECTIVE_NAME = "DICTYPES";

    @Db
    SysDictMapper dictMapper;

    @Inject
    YoucanCacheService cacheService;

    @Override
    public boolean hasEnd() {
        return true;
    }

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {
        List<SysDict> list = this.cacheService.getOrStoreTag(
            CacheConstants.SYS_DICT_KEY + ":" + DIRECTIVE_NAME + ":all",
            CacheConstants.CACHE_SECONDS_ONE_DAY, new Supplier<List<SysDict>>() {
                @Override
                public List<SysDict> get() {
                    /*
                     * 查询字典类型列表
                     */
                    return DictTypeDirective.this.dictMapper.selectListByQuery(QueryWrapper.create()
                        .where(SYS_DICT.STATUS.eq(BeanStatus.ON.name())).orderBy(new QueryOrderBy(SYS_DICT.CREATED_DATETIME))
                    );
                }

            } , CacheConstants.SYS_DICT_TAG);

        scope.setLocal(this.getPara("var", scope, DIRECTIVE_NAME.toLowerCase()), list);

        this.renderBody(env, scope, writer);
    }

}
